package com.zhen.aikan.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.zhen.aikan.constant.RedisConstants;
import com.zhen.aikan.entity.User;
import com.zhen.aikan.service.IUtilService;
import com.zhen.aikan.util.StringUtils;
import com.zhen.aikan.util.VerificationCodeUtil;
import com.zhen.aikan.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 工具服务
 * @author LiJiaZhen
 * @date 2023/9/19 23:07
 */
@Service
public class UtilServiceImpl implements IUtilService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final Logger logger = LoggerFactory.getLogger(UtilServiceImpl.class);
    @Override
    public void getVerificationCode(String email) {
        //1、校验邮箱格式
        if (!Validator.isEmail(email)) {
            logger.error("邮箱格式错误");
            return;
        }
        //2、生成验证码
        String verificationCode = RandomUtil.randomNumbers(4);
        //3、保存验证码到redis 5分钟过期
        stringRedisTemplate.opsForValue().set(RedisConstants.REGISTER_CODE_KEY+email,
                verificationCode,
                RedisConstants.LOGIN_CODE_TTL,
                TimeUnit.MINUTES);
        //4、发送验证码
        VerificationCodeUtil.sendVerificationCode(email,verificationCode);
    }

    @Override
    public boolean verifyCode(String email,String code) {
        //1、校验邮箱格式
        if (!Validator.isEmail(email)) {
            logger.error("邮箱格式错误");
            return false;
        }
        //从redis获取验证码
        String vCode = stringRedisTemplate.opsForValue().get(RedisConstants.REGISTER_CODE_KEY + email);
        return code.equals(vCode);
    }

    @Override
    public Map<Object, Object> getUserByToken(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        //判断用户是否还存在
        if(userMap.isEmpty()){
            return null;
        }
        //更新redis数据的过期时间
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.DAYS);
        return userMap;
    }
}
